<?php

namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller {

    //登录跳转
    public function index(){
        echo '<script> location.href = "'.U('Login/login').'" </script>';
    }

    //用户登录页面
    public function login() {
        //用户的登录检测
        $id = $_SESSION['home']['uid'];
        //判断
        if (!empty($id)) {
            $this->error('您已经登录了呢!', U('News/index'));
            die;
        }

        $this->assign('test', '用户登录页面');
        $this->assign('ajaxurl', U('Login/logindo'));
        $this->assign('yesstr', '登录成功!');
        $this->assign('nostr', '登录失败!');
        $this->assign('lesstr', '请确保帐号为锁定且已验证邮箱!!');
        $this->display();
    }

    //极验验证
    public function jyan() {
        require_once '/Public/Jyan/lib/class.geetestlib.php';
        require_once '/Public/Jyan/config/config.php';
        $GtSdk = Jy(CAPTCHA_ID, PRIVATE_KEY);
        session_start();
        // $user_id             = mt_rand();
        $status               = $GtSdk->pre_process($user_id);
        $_SESSION['gtserver'] = $status;
        // $_SESSION['user_id'] = $user_id;
        echo $GtSdk->get_response_str();
    }

    //人脸验证登录
	public function facecheck(){
		if(IS_AJAX){
			// $username=I('post.username','','string');
			$feature=I('post.feature','','string');
			$user=M('User');
            $info=M('UserInfo');
			$userBase=$user->where('feature="'.$feature.'"')->find();
            $userInfo = $info->find($userBase['user_id']);
            if ($userBase && $userInfo) {
                //在SESSION中记录用户的信息
                $_SESSION['home']['uid']      = $userBase['user_id'];
                $_SESSION['home']['uname']    = $userBase['username'];
                $_SESSION['home']['nickname'] = $userInfo['nickname'];
                $_SESSION['home']['photo']    = $userInfo['photo'];
                $data = array(
                    'user_id'     => $userBase['user_id'],
                    'lasttime'    => $_SERVER['REQUEST_TIME'],
                    'lastip'      => $_SERVER['REMOTE_ADDR'],
                    'online' => 1,
                );
                $user->save($data);
                $result=array('status'=>1);
            }else{
                $result=array('status'=>0);
            }
            $this->ajaxReturn($result);
		}
	}

    //用户登录处理页面
    public function logindo() {
        // var_dump($_POST);die();
        //这里请使用ajax访问
        if (IS_AJAX) {
            //实例化数据表对象
            $user = M('User');
            // var_dump($_POST);die;
            //核实用户信息
            //处理得到的用户账号密码
            session_start();
            $test = I('post.pd');
            $data['zz_user.username'] = htmlspecialchars($test[0]);
            $data['zz_user.password'] = md5($test[1]);
            // $datapd = !empty($test[2]) ? true : false;
            //查询结果
            $res = $user
                ->where($data)
                ->join('zz_user_info ON zz_user.user_id  = zz_user_info.user_id')
                ->select();
            $res = $res[0];
            // echo $user -> _sql();
            // var_dump($res);die;
            if ($_SESSION['gtserver'] == 1) {
                if ($res) {
                    //判断帐号未被锁定 并且 邮箱以验证
                    // echo $res['email_state'];die;
                    if ($res['lock'] <= 10 and $res['email_state'] == 1) {
                        //在SESSION中记录用户的信息
                        $_SESSION['home']['uid']      = $res['user_id'];
                        $_SESSION['home']['uname']    = $res['username'];
                        $_SESSION['home']['nickname'] = $res['nickname'];
                        $_SESSION['home']['photo']    = $res['photo'];
                        //修改最后登录的时间和登录的IP
                        $arr = array(
                            'user_id'  => $_SESSION['home']['uid'],
                            'lasttime' => $_SERVER['REQUEST_TIME'],
                            'lastip'   => $_SERVER['REMOTE_ADDR'],
                            'online'   => '1',
                        );
                        $user->save($arr);
                        //当登录成功的时候
                        echo 'yes';
                        die;
                    } else {
                        //当帐号被锁定 或者邮箱未验证时
                        echo 'les';
                    }
                } else {
                    //数据库中没有匹配的数据时
                    echo 'no';
                }
            }
        } else {
            //当用户使用非ajax方式访问时
            $this->error('非法操作');
        }
    }

    //用户登出处理页面
    public function signout() {
        //得到当前的用户ID
        $id = $_SESSION['home']['uid'];
        //修改用户的登录状态
        $user_info = M('user');
        $data['online'] = '0';
        $user_info -> where('user_id='.$id) -> save($data);
        //清空SESSION内容
        // session_unset();
        // session_destroy();
        unset($_SESSION['home']);
        //跳转到登录页面
        $this->success('登出成功! 正在跳转到登录页面~', U('Login/login'), 2);
    }



    //用户注册页面
    public function signup() {
        $this->assign('test', '用户注册页面');
        $this->display();
    }

    //用户注册处理用ajax脚本
    public function signupdo() {
        $user = M('User');
        $user->startTrans();

        //准备用户基本数据
        $nowTime  = $_SERVER['REQUEST_TIME'];
        $nowIp    = $_SERVER['REMOTE_ADDR'];
        $username = I('post.username');
        $password = I('post.password');
        $userBase = array(
            'username'    => $username,
            'password'    => md5($password),
            'regtime'     => $nowTime,
            'regip'       => $nowIp,
            'lasttime'    => $nowTime,
            'lastip'      => $nowIp,
            'lock'        => 0,
            'email_token' => md5($username . $password),
            'email_state' => 0,
            'scan_state'  => 0,
            'online'      => 0,
            'feature'     => '',
        );
        // var_dump($userBase);

        //自动验证
        $rules = array(
            array('username', 'email', '请填写正确的邮箱！'),
            array('username', '', '邮箱已经存在！', 0, 'unique', 1),
            array('password', 'require', '请填写密码！'),
        );

        //验证入库用户基本信息
        if ($user->validate($rules)->create($userBase)) {
            $id = $user->add();
        } else {
            $this->error($user->getError());
        }

        //准备用户详细信息
        $userInfo = array(
            'user_id'   => $id,
            'tag'       => '',
            'nickname'  => trim(I('post.nickname')),
            'sex'       => I('post.sex', '2', 'int'),
            'area'      => '',
            'birthday'  => strtotime(I('post.birthday', date('Y-m-d'), 'string')),
            'signature' => I('post.signature', ''),
            'photo'     => '/Resource/default_photo.png',
            'exp'       => 0,
            'sign'      => 0,
            'vipday'    => 0
        );
        //自动验证
        $rules = array(
            array('nickname', 'require', '请填写您的昵称！'),
        );
        //验证入库用户详细信息
        $info = M('UserInfo');
        if ($userInfo = $info->validate($rules)->create($userInfo)) {
            if ($info->add()) {
                $user->commit();
                $title       = '欢迎注册众众网(请不要回复此邮件)';
                $username    =$userBase['username'];
                $email_token =$userBase['email_token'];
                $nickname    =$userInfo['nickname'];
                $activeLink = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/login/email', array('token' => $email_token));
                $content    = '<table style="margin: 25px auto;" border="0" cellspacing="0" cellpadding="0" width="648" align="center">
    <tbody>
    <tr><td style ="color:#2590BC;"><h1 style="margin-bottom:10px;">众众网</h1></td></tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 20px 20px 0px; background: none repeat scroll 0% 0% #ffffff; border-top: 5px solid #2590BC; border-right: 1px solid #66ABC7;">
    <p>' . $nickname . ', 你好 </p>
    </td>
    </tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 10px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <p>您已经成功注册为<strong>众众网</strong>用户！</p>
    <p style="font-weight:bold">请点击以下链接激活此帐号：<br>
        <a href="' . $activeLink . '">' . $activeLink . '</a></p>
    </td>
    </tr>
    <tr>
    <td style="border-bottom: 1px solid #66ABC7; border-left: 1px solid #66ABC7; padding: 0px 20px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <hr style="color:#ccc;">
    <p style="color:#2590BC;font-size:9pt;">想了解更多信息，请关注众众网</p>
    </td>
    </tr>
    </tbody>
    </table>';
                //发送邮件
                sendMail($username, $title, $content);
                // $this->success('注册成功！请留意您的邮箱以激活您的账号！', U('Home/Login/login'), 3);
                echo '
                <title>邮件已发送</title>
                <div>
                    <h1>邮件已发送</h1>
                    <div class="msg-box">
                        <p>已向你的邮箱 '.$username.' 发送了一封验证邮件。<!--<a href="#nogo">去邮箱收信&gt;&gt;</a>--></p>
                        <p>没收到？<a href="javascript:void(0);" onclick="repeatSend()">再次发送验证邮件&gt;&gt;</a></p>
                    </div>
                </div>
                <script>
                    function repeatSend(){
                        var img=new Image();
                        img.src="'.U('Home/Login/emailrepeat',array('email'=>$username)).'";
                    }
                </script>
                ';
            } else {
                $user->rollback();
                $this->error('出错了...', '', 3);
            }
        } else {
            $this->error($info->getError());
        }
    }

    public function emailrepeat(){
        $user=M('User');
        $info=M('UserInfo');
        $userBase=$user->field('user_id,username,email_token')->where('username="'.trim(I('get.email')).'"')->find();
        $userInfo=$info->field('nickname')->where('user_id='.$userBase['user_id'])->find();
        if($userBase && $userInfo){
            $title       = '欢迎注册众众网(请不要回复此邮件)';
            $username    =$userBase['username'];
            $email_token =$userBase['email_token'];
            $nickname    =$userInfo['nickname'];
            $activeLink = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/Login/email', array('token' => $email_token));
            $content    = '<table style="margin: 25px auto;" border="0" cellspacing="0" cellpadding="0" width="648" align="center">
    <tbody>
    <tr><td style ="color:#2590BC;"><h1 style="margin-bottom:10px;">众众网</h1></td></tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 20px 20px 0px; background: none repeat scroll 0% 0% #ffffff; border-top: 5px solid #2590BC; border-right: 1px solid #66ABC7;">
    <p>' . $nickname . ', 你好 </p>
    </td>
    </tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 10px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <p>您已经成功注册为<strong>众众网</strong>用户！</p>
    <p style="font-weight:bold">请点击以下链接激活此帐号：<br>
    <a href="' . $activeLink . '">' . $activeLink . '</a></p>
    </td>
    </tr>
    <tr>
    <td style="border-bottom: 1px solid #66ABC7; border-left: 1px solid #66ABC7; padding: 0px 20px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <hr style="color:#ccc;">
    <p style="color:#2590BC;font-size:9pt;">想了解更多信息，请关注众众网</p>
    </td>
    </tr>
    </tbody>
    </table>';
            //发送邮件
            sendMail($username, $title, $content);
        }
    }

    //邮箱验证页
    public function email() {
        $this->assign('title', '邮箱验证');
        $this->display();
    }

    //邮箱验证处理
    public function emaildo() {
        $token    = I('get.token');
        $user     = M('User');
        $info     = M('UserInfo');
        $userBase = $user->where("email_token='%s'", $token)->find();
        $userInfo = $info->find($userBase['user_id']);
        if ($userBase && $userInfo) {
            if ($userBase['email_state'] == 1) {
                unset($_SESSION['home']);
                $this->error('您的邮箱早已验证，请不要再来调戏本宝宝！', U('Home/Login/login'), 3);
            } else {
                //在SESSION中记录用户的信息
                $_SESSION['home']['uid']      = $userBase['user_id'];
                $_SESSION['home']['uname']    = $userBase['username'];
                $_SESSION['home']['nickname'] = $userInfo['nickname'];
                $_SESSION['home']['photo']    = $userInfo['photo'];

                $data = array(
                    'user_id'     => $userBase['user_id'],
                    'lasttime'    => $_SERVER['REQUEST_TIME'],
                    'lastip'      => $_SERVER['REMOTE_ADDR'],
                    'email_state' => 1,
                    'online' => 1,
                );
                $user->save($data);

                //初始化新用户数据表
                $albumsData1 = array(
                    'albums_name' => '贴图相册',
                    'albums_type' => 0,
                    'user_id'     => $userBase['user_id'],
                    'time'        => $_SERVER['REQUEST_TIME'],
                );
                $albumsData2 = array(
                    'albums_name' => '共享相册',
                    'albums_type' => 1,
                    'user_id'     => $userBase['user_id'],
                    'time'        => $_SERVER['REQUEST_TIME'],
                );
                $albums = M('albums');
                $albums->add($albumsData1);
                $albums->add($albumsData2);

                $this->success('邮箱验证成功！', U('Home/News/index'), 1);
            }
        } else {
            $this->error('验证失败！请检查您的邮箱号!', '', 3);
        }
    }

    //更新扫描状态
    public function scando(){
        $token    = I('get.token');
        $user     = M('User');
        $data['scan_state']=1;
        $user->where("email_token='%s'", $token)->save($data);
        echo '<script>window.close();</script>';
    }

    //获取扫描状态
    public function scancheck(){
        if(IS_AJAX){
            $token    = I('get.token');
            $user     = M('User');
            $result   = $user->where("email_token='%s'", $token)->find();
            if($result && $result['scan_state']==1){
                $this->ajaxReturn(array(
                    'status'=>1
                ));
            }else{
                $this->ajaxReturn(array(
                    'status'=>0
                ));
            }
        }
    }

    //重置密码页面
    public function repwd() {
        $email=I('get.email','','validate_email');
        $this->assign('email', $email);
        $this->assign('title', '重置密码页面');
        $this->display();
    }
    //重置密码填写页面
    public function repwdedit() {
        $this->assign('title', '重置密码页面');
        $this->display();
    }

    //重置密码操作页
    public function repwddo() {
        // var_dump($_POST);
        $newToken=I('post.token','','string');
        $email=I('post.email','','validate_email');
        $password=I('post.password','','string');
        $len=strlen($password);

        if($len<6 || $len>18){
            $this->error('请输入6到18位的密码！');
        }

        $user=M('User');
        $res=$user->where('username="'.$email.'"')->find();
        if($res){
            $token=$res['email_token'];
            $id=$res['user_id'];
            if($newToken==md5($token.$id)){
                $data=array(
                    'user_id'=>$id,
                    'password'=>md5($password)
                );
                if($user->create($data)){
                    $user->save($data);
                    if(isset($_SESSION['home'])){
                        unset($_SESSION['home']);
                    }
                    $this->success('密码修改成功！',U('Home/Login/login'),3);
                }else{
                    $this->error($info->getError());
                }
            }
        }else{
            $this->error('密码重置失败！没有该邮箱用户！','',3);
        }

    }

    //发送重置密码邮件
    public function repwdsend() {
        $email=I('get.email','','validate_email');
        $user=M('User');
        $userBase=$user->where('username="'.$email.'"')->find();
        $info=M('UserInfo');
        $userInfo=$info->where('user_id='.$userBase['user_id'])->find();
        if($userBase && $userInfo){
            $title       = '这是一封密码重置邮件，来自众众网(请不要回复此邮件)';
            $username    =$userBase['username'];
            $email_token =md5($userBase['email_token'].$userBase['user_id']);
            $nickname    =$userInfo['nickname'];
            $activeLink = 'http://' . $_SERVER['HTTP_HOST'] . U('Home/Login/repwdedit', array('email'=>$username,'token' => $email_token));
            $content    = '<table style="margin: 25px auto;" border="0" cellspacing="0" cellpadding="0" width="648" align="center">
    <tbody>
    <tr><td style ="color:#2590BC;"><h1 style="margin-bottom:10px;">众众网</h1></td></tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 20px 20px 0px; background: none repeat scroll 0% 0% #ffffff; border-top: 5px solid #2590BC; border-right: 1px solid #66ABC7;">
    <p>' . $nickname . ', 你好 </p>
    </td>
    </tr>
    <tr>
    <td style="border-left: 1px solid #66ABC7; padding: 10px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <p>这是一封来自<strong>众众网</strong>的密码重置邮件！</p>
    <p style="font-weight:bold">请点击以下链接重置此帐号密码：<br>
    <a href="' . $activeLink . '">' . $activeLink . '</a></p>
    </td>
    </tr>
    <tr>
    <td style="border-bottom: 1px solid #66ABC7; border-left: 1px solid #66ABC7; padding: 0px 20px 20px; background: none repeat scroll 0% 0% #ffffff; border-right: 1px solid #66ABC7;">
    <hr style="color:#ccc;">
    <p style="color:#2590BC;font-size:9pt;">想了解更多信息，请关注众众网</p>
    </td>
    </tr>
    </tbody>
    </table>';
            //发送邮件
            sendMail($username, $title, $content);

            echo '
            <title>密码重置邮件已发送</title>
            <div>
                <h1>密码重置邮件已发送</h1>
                <div class="msg-box">
                    <p>已向你的邮箱 '.$username.' 发送了一封密码重置邮件。</p>
                </div>
            </div>';
        }else{
            $this->error('你在逗我？根本没这个用户邮箱！','',3);
        }
    }
}
